package com.joysuch.wwyt.api.basedata.service.impl;

import cn.zlg.common.enums.BusinessTypeEnum;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.joysuch.wwyt.api.basedata.service.BaseImageSyncService;
import com.joysuch.wwyt.core.entity.BaseConfig;
import com.joysuch.wwyt.core.entity.BaseImageRepository;
import com.joysuch.wwyt.core.enums.BaseConfigCodes;
import com.joysuch.wwyt.core.repository.BaseImageRespositoryDao;
import com.joysuch.wwyt.core.service.BaseConfigService;
import com.joysuch.wwyt.dzhapi.bean.ApiBaseConfigBean;
import com.joysuch.wwyt.dzhapi.bean.ApiBaseImageRepositoryBean;
import com.joysuch.wwyt.dzhapi.dto.BuildDataDto;
import com.joysuch.wwyt.dzhapi.mapper.ApiBaseConfigMapper;
import com.joysuch.wwyt.dzhapi.mapper.ApiBaseImageRepositoryMapper;
import com.joysuch.wwyt.log.service.FileUploadLogService;
import com.joysuch.wwyt.monitoringcenter.bean.LocateLoginRespDto;
import com.joysuch.wwyt.monitoringcenter.bean.SyncBatchDataReturnBean;
import com.joysuch.wwyt.monitoringcenter.service.LocateServerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;
import java.util.Optional;

/**
 * @Author ZhaoQiuWei
 * @Date 2021/7/22 17:03
 */
@Service
@Slf4j
public class BaseImageSyncServiceImpl implements BaseImageSyncService {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private BaseConfigService baseConfigService;
    @Autowired
    private LocateServerService locateServerService;
    @Autowired
    private BaseImageRespositoryDao baseImageRespositoryDao;
    @Autowired
    private FileUploadLogService fileUploadLogService;
    @Autowired
    private ApiBaseImageRepositoryMapper imageRepositoryMapper;
    @Autowired
    private ApiBaseConfigMapper configMapper;

    @Value("${wwyt.image.upload.dir}")
    private String imageUploadDir;

    /**
     * 同步头像
     *
     * @param imgId
     * @param uniqueId   人员/承包商人员 uniqueId
     * @param buildId
     * @param loginToken
     * @param failFlag   同步结果
     * @return
     */
    @Override
    public byte syncPeopleHeadImage(Long imgId, String uniqueId, String buildId, String loginToken, byte failFlag) {
        if (imgId != null) {
            log.info("头像同步Start...................");
            Optional<BaseImageRepository> obr = baseImageRespositoryDao.findById(imgId);
            if (!obr.isPresent()) {
                return failFlag;
            }
            failFlag = 1;
            BaseConfig config = baseConfigService.findFirstConfig(BaseConfigCodes.LOCATE_SERVER_V3_PEOPLE_HEAD_SAVE);
            if (config == null) {
                log.error("config is null: " + BaseConfigCodes.LOCATE_SERVER_V3_PEOPLE_HEAD_SAVE);
                return failFlag;
            }
            BaseImageRepository repository = obr.get();
            FileSystemResource fr = new FileSystemResource(imageUploadDir + File.separator + repository.getOriginPath());
            MultiValueMap<String, Object> multipartRequest = new LinkedMultiValueMap<>();
            multipartRequest.add("file", fr);
            multipartRequest.add("buildId", buildId);
            multipartRequest.add("uniqueId", uniqueId);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
            headers.set("token", loginToken);
            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity(multipartRequest, headers);
            String url = locateServerService.getIpPortUrl(config.getValue());
            //发起调用
            log.info("头像参数=====" + requestEntity.getBody());
            ResponseEntity<LocateLoginRespDto> response = null;
            try {
                response = restTemplate.postForEntity(url, requestEntity, LocateLoginRespDto.class);
            } catch (RestClientException e) {
                log.error("头像同步失败 e{}", e);
            }
            if (response != null && response.getStatusCode() != null && response.getStatusCode().value() == HttpStatus.OK.value() && response.getBody() != null) {
                LocateLoginRespDto body = response.getBody();
                if (StringUtils.isNotBlank(body.getErrMsg())) {
                    log.error("头像同步失败, imgId:" + imgId + " msg:" + body.getErrMsg());
                    fileUploadLogService.savaLog(BusinessTypeEnum.IMAGE.getBusinessCode(), BusinessTypeEnum.IMAGE.getBusinessName(), repository.getOriginPath(), 0, "头像同步失败: msg: " + body.getErrMsg());
                } else {
                    if (body.getCode() == 0) {
                        failFlag = 0;
                        log.info("头像同步成功, imgId:" + imgId);
                        fileUploadLogService.savaLog(BusinessTypeEnum.IMAGE.getBusinessCode(), BusinessTypeEnum.IMAGE.getBusinessName(), repository.getOriginPath(), 1, "头像同步成功");
                    } else {
                        log.error("头像同步失败, imgId:{}，errorBody:{}", imgId, body);
                    }
                }
            } else {
                log.error("头像同步失败, imgId:{}，response:{}", imgId, JSON.toJSONString(response));
            }
            log.info("头像同步End...................");
        }
        return failFlag;
    }

    @Override
    public byte apiSyncPeopleHeadImage(Long imgId, String uniqueId, String buildId, String loginToken, byte failFlag, BuildDataDto dto) {
        if (imgId != null) {
            log.info("头像同步Start...................");
            ApiBaseImageRepositoryBean apiBaseImageRepositoryBean = imageRepositoryMapper.selectById(imgId);
            if (apiBaseImageRepositoryBean == null) {
                return failFlag;
            }
            failFlag = 1;
            ApiBaseConfigBean config = configMapper.findConfig(dto.getTenentId(), dto.getOrgCode(), BaseConfigCodes.LOCATE_SERVER_V3_PEOPLE_HEAD_SAVE);
            if (config == null) {
                log.error("config is null: " + BaseConfigCodes.LOCATE_SERVER_V3_PEOPLE_HEAD_SAVE);
                return failFlag;
            }
            FileSystemResource fr = new FileSystemResource(imageUploadDir + File.separator + apiBaseImageRepositoryBean.getOriginPath());
            MultiValueMap<String, Object> multipartRequest = new LinkedMultiValueMap<>();
            multipartRequest.add("file", fr);
            multipartRequest.add("buildId", buildId);
            multipartRequest.add("uniqueId", uniqueId);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
            headers.set("token", loginToken);
            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity(multipartRequest, headers);
            String url = locateServerService.getApiIpPortUrl(config.getValue(),dto);
            //发起调用
            log.info("头像参数=====" + requestEntity.getBody());
            ResponseEntity<LocateLoginRespDto> response = null;
            try {
                response = restTemplate.postForEntity(url, requestEntity, LocateLoginRespDto.class);
            } catch (RestClientException e) {
                log.error("头像同步失败 e{}", e);
            }
            if (response != null && response.getStatusCode() != null && response.getStatusCode().value() == HttpStatus.OK.value() && response.getBody() != null) {
                LocateLoginRespDto body = response.getBody();
                if (StringUtils.isNotBlank(body.getErrMsg())) {
                    log.error("头像同步失败, imgId:" + imgId + " msg:" + body.getErrMsg());
                    fileUploadLogService.savaLog(BusinessTypeEnum.IMAGE.getBusinessCode(), BusinessTypeEnum.IMAGE.getBusinessName(), apiBaseImageRepositoryBean.getOriginPath(), 0, "头像同步失败: msg: " + body.getErrMsg());
                } else {
                    if (body.getCode() == 0) {
                        failFlag = 0;
                        log.info("头像同步成功, imgId:" + imgId);
                        fileUploadLogService.savaLog(BusinessTypeEnum.IMAGE.getBusinessCode(), BusinessTypeEnum.IMAGE.getBusinessName(), apiBaseImageRepositoryBean.getOriginPath(), 1, "头像同步成功");
                    } else {
                        log.error("头像同步失败, imgId:{}，errorBody:{}", imgId, body);
                    }
                }
            } else {
                log.error("头像同步失败, imgId:{}，response:{}", imgId, JSON.toJSONString(response));
            }
            log.info("头像同步End...................");
        }
        return failFlag;
    }

    /**
     * @param file
     * @param originPath 图片路径
     * @param uniqueId
     * @return
     */
    @Override
    public boolean syncPeopleCap(MultipartFile file, String originPath, String uniqueId) {
        log.info("帽子同步Start......");
        boolean syncFlag = false;
        BaseConfig config = baseConfigService.findFirstConfig(BaseConfigCodes.LOCATE_SERVER_V3_PEOPLE_CAP_SAVE);
        String buildId = locateServerService.getBuildId();
        if (StringUtils.isBlank(buildId)) {
            log.error("buildId is null");
            return syncFlag;
        }
        String loginToken = locateServerService.getLoginToken();
        if (StringUtils.isBlank(loginToken)) {
            log.error("loginToken is null");
            return syncFlag;
        }
        if (config == null) {
            log.error("config is null: " + BaseConfigCodes.LOCATE_SERVER_V3_PEOPLE_CAP_SAVE);
            return syncFlag;
        }
        FileSystemResource fr = new FileSystemResource(imageUploadDir + File.separator + originPath);
        MultiValueMap<String, Object> multipartRequest = new LinkedMultiValueMap<>();
        multipartRequest.add("iconFile", fr);
        multipartRequest.add("warningFile", fr);
        multipartRequest.add("buildId", buildId);
        multipartRequest.add("uniqueId", uniqueId);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        headers.set("token", loginToken);
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity(multipartRequest, headers);
        String url = locateServerService.getIpPortUrl(config.getValue());
        //发起调用
        log.info("帽子参数=====" + requestEntity.getBody());
        ResponseEntity<LocateLoginRespDto> response = restTemplate.postForEntity(url, requestEntity, LocateLoginRespDto.class);
        if (response.getStatusCode() != null && response.getStatusCode().value() == HttpStatus.OK.value() && response.getBody() != null) {
            LocateLoginRespDto body = response.getBody();
            if (StringUtils.isNotBlank(body.getErrMsg())) {
                log.error("帽子同步失败, uniqueId:" + uniqueId + " msg:" + body.getErrMsg());
                fileUploadLogService.savaLog(BusinessTypeEnum.IMAGE.getBusinessCode(), BusinessTypeEnum.IMAGE.getBusinessName(), file.getOriginalFilename(), 0, "帽子同步失败: " + body.getErrMsg());
            } else {
                if (body.getCode() == 0) {
                    syncFlag = true;
                    log.info("帽子同步成功, uniqueId:" + uniqueId);
                    fileUploadLogService.savaLog(BusinessTypeEnum.IMAGE.getBusinessCode(), BusinessTypeEnum.IMAGE.getBusinessName(), file.getOriginalFilename(), 1, "帽子同步成功");
                } else {
                    log.error("帽子同步失败, uniqueId:{}，errorBody:{}", uniqueId, body);
                }
            }
        } else {
            log.error("帽子同步失败, uniqueId:{}，errorCode:{}", uniqueId, response.getStatusCodeValue());
        }
        log.info("帽子同步End......");
        return syncFlag;
    }

    /**
     * 帽子删除同步
     *
     * @return
     */
    @Override
    public boolean SyncDeleteCaps(Long id) {
        log.info("帽子删除同步Start......");
        boolean syncFlag = false;
        String buildId = locateServerService.getBuildId();
        if (StringUtils.isBlank(buildId)) {
            log.error("buildId is null");
            return syncFlag;
        }
        Long uniqueId = baseImageRespositoryDao.getUniqueIdByTypeId(id);
        if (uniqueId == null) {
            log.error("uniqueId is null");
            return syncFlag;
        }
        BaseConfig config = baseConfigService.findFirstConfig(BaseConfigCodes.LOCATE_SERVER_V3_PEOPLE_CAP_DELETE);
        if (config == null) {
            log.error("config is null: " + BaseConfigCodes.LOCATE_SERVER_V3_PEOPLE_CAP_DELETE);
            return syncFlag;
        }
        MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        map.add("buildId", buildId);
        map.add("uniqueId", uniqueId);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        headers.set("token", locateServerService.getLoginToken());
        headers.set("buildId", buildId);
        HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(map, headers);
        ResponseEntity<LocateLoginRespDto> response = restTemplate.postForEntity(locateServerService.getIpPortUrl(config.getValue()), request, LocateLoginRespDto.class);
        if (response.getStatusCode() != null && response.getStatusCode().value() == HttpStatus.OK.value() && response.getBody() != null) {
            LocateLoginRespDto body = response.getBody();
            if (StringUtils.isNotBlank(body.getErrMsg())) {
                log.error("帽子删除同步失败, uniqueId:" + uniqueId + " msg:" + body.getMsg());
                fileUploadLogService.savaLog(BusinessTypeEnum.IMAGE.getBusinessCode(), BusinessTypeEnum.IMAGE.getBusinessName(), "typeId: " + id, 0, "帽子删除同步失败");
            } else {
                if (body.getCode() == 0) {
                    syncFlag = true;
                    log.info("帽子删除同步成功, uniqueId:" + uniqueId);
                    fileUploadLogService.savaLog(BusinessTypeEnum.IMAGE.getBusinessCode(), BusinessTypeEnum.IMAGE.getBusinessName(), "typeId: " + id, 1, "帽子删除同步成功");
                } else {
                    log.error("帽子删除同步失败, uniqueId:{}，errorBody:{}", uniqueId, body);
                }
            }
        } else {
            log.error("帽子删除同步失败, uniqueId:{}，errorCode:{}", uniqueId, response.getStatusCodeValue());
        }
        log.info("帽子删除同步End......");
        return syncFlag;
    }

    /**
     * 批量同步人员头像
     *
     * @param path
     */
    @Override
    public void batchPeopleHeadImages(String path, String buildId, String token, String peopleType) {
        log.info(peopleType + "__头像批量同步Start");
        BaseConfig config;
        if (peopleType.equals("user")) {
            config = baseConfigService.findFirstConfig(BaseConfigCodes.LOCATE_SERVER_V3_PEOPLE_HEADS_SAVE);
        } else {
            config = baseConfigService.findFirstConfig(BaseConfigCodes.LOCATE_SERVER_V3_STAFF_HEADS_SAVE);
        }

        if (config == null) {
            log.error(peopleType + " urlConfig is null ...");
            return;
        }
        FileSystemResource fr = new FileSystemResource(path);
        MultiValueMap<String, Object> multipartRequest = new LinkedMultiValueMap<>();
        multipartRequest.add("file", fr);
        multipartRequest.add("buildId", buildId);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        headers.set("token", token);
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity(multipartRequest, headers);
        String url = locateServerService.getIpPortUrl(config.getValue());
        //发起调用
        log.info(peopleType + "__头像批量同步参数=====" + requestEntity.getBody());
        ResponseEntity<LocateLoginRespDto> response = restTemplate.postForEntity(url, requestEntity, LocateLoginRespDto.class);
        if (response.getStatusCode() != null && response.getStatusCode().value() == HttpStatus.OK.value() && response.getBody() != null) {
            LocateLoginRespDto body = response.getBody();
            if (StringUtils.isNotBlank(body.getErrMsg()) || (body.getData() != null && !CollectionUtils.isEmpty((List<SyncBatchDataReturnBean>) body.getData()))) {
                log.error(peopleType + "__头像批量同步失败, path:" + path + " msg:" + body.getMsg());
                List<SyncBatchDataReturnBean> data = (List<SyncBatchDataReturnBean>) body.getData();
                if (!CollectionUtils.isEmpty((List<SyncBatchDataReturnBean>) body.getData())) {
                    String str = JSON.toJSONString(data);
                    List<SyncBatchDataReturnBean> list = JSONObject.parseArray(str, SyncBatchDataReturnBean.class);
                    log.error(peopleType + "_returnData: " + list);
                    fileUploadLogService.savaLog(BusinessTypeEnum.IMAGE.getBusinessCode(), BusinessTypeEnum.IMAGE.getBusinessName(), "path: " + path, 0, peopleType + "__头像批量同步失败: " + list);
                }
            } else {
                if (body.getCode() == 0) {
                    log.info(peopleType + "__头像批量同步成功, path:" + path);
                    fileUploadLogService.savaLog(BusinessTypeEnum.IMAGE.getBusinessCode(), BusinessTypeEnum.IMAGE.getBusinessName(), "path: " + path, 1, peopleType + "__头像批量同步成功");
                } else {
                    log.error(peopleType + "__头像批量同步失败, path:{}，errorBody:{}", path, body);
                }
            }
        } else {
            log.error(peopleType + "__头像批量同步失败, path:{}，errorCode:{}", path, response.getStatusCodeValue());
        }
        log.info(peopleType + "__头像批量同步End...................");
    }


}
